package com.xiaoyang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyang.dto.ResultDTO;
import com.xiaoyang.dto.UserDTO;
import com.xiaoyang.helper.AESHelper;
import com.xiaoyang.helper.DESHelper;
import com.xiaoyang.helper.GZIPHelper;
import com.xiaoyang.mapper.UserMapper;
import com.xiaoyang.pojo.User;
import com.xiaoyang.service.AutoLocationService;
import com.xiaoyang.service.UserService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.jetbrains.annotations.TestOnly;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author guoziyang
 * @create 2020/9/21 5:20 下午
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AutoLocationService autoLocationService;

    /**
     * 保存用户信息
     *
     * @param userDTO
     * @return
     */
    @Override
    public ResultDTO saveUserInfo(UserDTO userDTO) {
        User user = new User();
        // 加密保存到数据库
        user.setUsername(AESHelper.encrypt(userDTO.getUsername()));
        user.setPassword(AESHelper.encrypt(userDTO.getPassword()));
        user.setUid(userDTO.getUid());
        // 获取extension
        String extension = DESHelper.getExtension(userDTO.getUsername());
        user.setExtension(GZIPHelper.compress(extension));
        user.setRealName(userDTO.getRealName());
        user.setUpdateTime(new Date());
        // 保存
        int i = userMapper.insertSelective(user);
        if (i < 1) {
            return new ResultDTO(3, "保存数据失败！");
        }
        return new ResultDTO();
    }

    /**
     * 判断用户是否存在
     *
     * @param username
     * @return
     */
    @Override
    public Boolean isUserExist(String username) {
        User user = new User();
        user.setUsername(AESHelper.encrypt(username));
        User searchUser = userMapper.selectOne(user);
        if (searchUser == null) {
            return false;
        }
        return true;
    }

    /**
     * 查找所有用户
     *
     * @return
     */
    @Override
    public List<User> findAllUser() {
        List<User> users = userMapper.selectAll();
        if (users.size() == 0) {
            return null;
        }
        return users;
    }

    @Override
    public String getRealName(UserDTO userDTO) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();

        String cookie = autoLocationService.getCookie(userDTO.getUsername(), userDTO.getPassword());
        Request request = new Request.Builder()
                .addHeader("Host", "thxy.campusphere.net")
                .addHeader("accept", "application/json, text/plain, */*")
                .addHeader("Origin", "https://thxy.campusphere.net")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 4.4.4; OPPO R11 Plus Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36")
                .addHeader("Cookie", cookie)
                .url("https://thxy.campusphere.net/portal/desktop/userDesktopInfo")
                .post(RequestBody.create("", null))
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();
            String resp = response.body().string();
            JSONObject jsonObject = JSON.parseObject(resp);
            String realName = jsonObject.getJSONObject("datas").getString("userName");
            return realName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int deleteUserByUid(String uid) {
        User user = new User();
        user.setUid(uid);
        int result = userMapper.delete(user);
        return result;
    }

    @Override
    public User findByExtension(String extension) {
        User user = new User();
        user.setExtension(extension);
        User searchUser = userMapper.selectOne(user);
        if (searchUser != null) {
            return user;
        }
        return null;
    }
}
